/**
 * 共享时间轴组件
 * 
 * 用途：为多个图表提供统一的时间轴显示，确保时间轴对齐
 * 方法：使用共同的时间范围和格式化逻辑
 * 原理：通过统一的时间计算和显示逻辑，保证不同图表的时间轴一致性
 */
package com.example.brain_wave.ui.components

import androidx.compose.foundation.layout.*
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.brain_wave.ui.components.BrainWaveDataPoint

/**
 * 时间轴数据类
 */
data class TimeAxisData(
    val startTime: Long,
    val endTime: Long,
    val timeLabels: List<String>
)

/**
 * 计算时间轴数据
 */
fun calculateTimeAxisData(dataPoints: List<BrainWaveDataPoint>): TimeAxisData? {
    if (dataPoints.isEmpty()) return null
    
    val startTime = dataPoints.first().timestamp
    val endTime = dataPoints.last().timestamp
    
    // 生成5个时间点的标签
    val timeLabels = listOf(0f, 0.25f, 0.5f, 0.75f, 1f).map { ratio ->
        val time = startTime + ((endTime - startTime) * ratio).toLong()
        formatTimeToHMS(time)
    }
    
    return TimeAxisData(startTime, endTime, timeLabels)
}

/**
 * 共享时间轴组件
 */
@Composable
fun SharedTimeAxis(
    timeAxisData: TimeAxisData?,
    textColor: Color = Color.White,
    modifier: Modifier = Modifier
) {
    if (timeAxisData == null) return
    
    // 调试信息
    println("SharedTimeAxis: 渲染时间轴 - timeLabels.size: ${timeAxisData.timeLabels.size}")
    
    Row(
        modifier = modifier.padding(top = 8.dp),
        horizontalArrangement = Arrangement.SpaceBetween
    ) {
        timeAxisData.timeLabels.forEach { label ->
            Text(
                text = label,
                color = textColor,
                fontSize = 10.sp
            )
        }
    }
}

/**
 * 格式化时间为 hh时mm分ss秒 格式
 */
private fun formatTimeToHMS(timestamp: Long): String {
    val calendar = java.util.Calendar.getInstance()
    calendar.timeInMillis = timestamp
    
    val hour = calendar.get(java.util.Calendar.HOUR_OF_DAY)
    val minute = calendar.get(java.util.Calendar.MINUTE)
    val second = calendar.get(java.util.Calendar.SECOND)
    
    return String.format("%02d时%02d分%02d秒", hour, minute, second)
}